import { observable, action } from 'mobx'
import * as api from 'lib/constants/api'
import { post } from 'lib/net'
import lrz from 'lrz'
import Toast from 'components/toast'
import Load from 'components/load'

class AddressModel {
  constructor (data) {
    if (data) {
      this.label = data.Name
      this.value = data.AreaCode
      this.children = []
      if (data.ChildList) {
        data.ChildList.map(item => {
          this.children.push(new AddressModel(item))
        })
      }
    }
  }
}

export default class JoinVM {
  constructor (props) {
    this.props = props
    this.PageInitialization()
  }

  // 用户名
  @observable userName = ''

  // 手机号
  @observable phoneNumber = ''

  // 性别
  @observable userGender = '请选择性别'

  // 性别样式
  @observable genderStyle = ''

  // 年龄
  @observable userAge = ''

  // 身份证号码
  @observable userIdNumber = ''

  // 验证码
  @observable userCode = ''

  // 所选城市value
  @observable cityCode = []

  // 所选城市样式
  @observable cityStyle = ''

  // 获取城市列表
  @observable addressList =[]

  // 身份证图片
  @observable idCardImg = `${require('../../images/idcardimg.png')}`
  @observable idCardImgs = ''

  // 验证码value
  @observable codeValue = '获取验证码'

  // 验证码样式class
  @observable codeClass = 'get-code'

  // 是否禁用按钮
  @observable codeDisable = false

  // 倒计时60秒
  @observable setTime = 59

  // 获取页面数据
  @action onChange = (v, key) => {
    switch (key) {
      case 'UserName':
        this.userName = v
        break
      case 'UserAge':
        this.userAge = v
        break
      case 'PhoneNumber':
        this.phoneNumber = v
        break
      case 'UserId':
        this.userIdNumber = v
        break
      case 'UserCode':
        this.userCode = v
        break
      case 'CityCode':
        this.cityStyle = 'cityStyle'
        this.cityCode = v
        break
      case 'Female':
        this.genderStyle = 'genderStyle'
        this.userGender = '女'
        break
      case 'Male':
        this.genderStyle = 'genderStyle'
        this.userGender = '男'
        break
    }
  }

  // 修改用户身份证信息
  @action handleImageChange = e => {
    let file = e.target.files[0]
    if (file && file.size <= 0) return
    this.compressImage(file)
    e.target.value = ''
  }

  // 压缩图片
  @action compressImage = file => {
    Toast.loading(1, '正在压缩')
    lrz(file, { width: 800 })
      .then(rst => {
        this.updateImage({ Base64: rst.base64, ImageName: file.name })
      }).catch(() => {
        this.loading = false
        Toast.fail('压缩失败')
      })
  }

  // 上传图片
  @action updateImage = async params => {
    Toast.loading(1, '正在上传')
    let res = await post(api.UPLOADIMA64, params)
    if (res.Success === true) {
      this.idCardImg = api.WZ_IMAGE_PATH + res.Value
      this.idCardImgs = res.Value
      Toast.success('上传成功')
    } else {
      Toast.fail('上传失败')
    }
  }

  // 倒计时
  @action task = () => {
    if (this.setTime === 0 && this.userCode !== '') {
      this.codeClass = 'get-code'
      this.codeValue = '获取验证码'
      this.codeDisable = false
      this.setTime = 59
      return
    } else if (this.setTime === 0 && this.userCode === '') {
      this.codeClass = 'get-code'
      this.codeValue = '重新获取'
      this.codeDisable = false
      this.setTime = 59
      return
    } else {
      this.codeDisable = true
      this.codeClass = 'get-coding'
      if (this.setTime < 10) {
        this.codeValue = '重新发送(0' + this.setTime + ')'
      } else {
        this.codeValue = '重新发送(' + this.setTime + ')'
      }
      this.setTime--
    }
    setTimeout(() => { this.task() }, 1000)
  }

  // 验证手机号是否符合正则
  @action phoneCodeValid = (number) => {
    this.number = number
    this.number = Number(this.myTrim(this.number, 'g'))
    let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
    if (!myreg.test(this.number)) {
      Toast.fail('请输入正确手机号')
      return false
    } else {
      return true
    }
  }

  // 去除字符串中的空格
  @action myTrim = (str, global) => {
    let result
    result = str.toString().replace(/(^\s+)|(\s+$)/g, '')
    if (global.toLowerCase() === 'g') {
      result = result.replace(/\s/g, '')
    }
    return result
  }

  // 身份证验证
  @action IdCodeValid = (code) => {
    var city = { 11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江 ', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北 ', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏 ', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外 ' }
    if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(code)) {
      Toast.fail('身份证号格式错误')
      return false
    } else if (!city[code.substr(0, 2)]) {
      Toast.fail('身份证号地址编码错误')
      return false
    } else {
      return true
    }
  }

  // 获取验证码事件
  @action handleGetCode = async () => {
    if (this.phoneCodeValid(this.phoneNumber) === true) {
      let params = { Phone: this.myTrim(this.phoneNumber, 'g'), Type: 4, Operate: 1 }
      let response = await post(api.GETCODE, params)
      if (response.Success) {
        this.task()
      } else {
        Toast.fail(response.Message)
      }
    }
  }

  // 提交申请
  @action handleSubmitApply = async () => {
    if (this.myTrim(this.userName, 'g') === '') {
      Toast.fail('姓名不能为空')
    } else if (this.userGender === '请选择性别') {
      Toast.fail('请选择性别')
    } else if (this.myTrim(this.userAge, 'g') === '') {
      Toast.fail('年龄不能为空')
    } else if (this.IdCodeValid(this.userIdNumber) === false) {
      return false
    } else if (this.phoneCodeValid(this.phoneNumber) === false) {
      return false
    } else if (this.myTrim(this.userCode, 'g') === '') {
      Toast.fail('验证码不能为空')
    } else if (this.cityCode[0] === undefined) {
      Toast.fail('请选择所在城市')
    } else if (this.idCardImg.startsWith('https://loans.shundaonetwork.com/Attach/Img') !== true) {
      Toast.fail('请上传手持身份证照片')
    } else {
      let params = {
        Code: this.userCode,
        Name: this.userName,
        Sex: (this.userGender !== '请选择性别') ? (this.userGender === '男' ? 1 : 0) : '',
        Age: this.userAge,
        PhoneNum: this.myTrim(this.phoneNumber, 'g'),
        Province: this.cityCode[0],
        City: this.cityCode[1],
        CardImage: this.idCardImgs,
        CardNum: this.userIdNumber
      }
      let response = await post(api.WZAPPLY, params)
      if (response.Success) {
        this.props.history.push('/promptSuccess')
        // window.location.back(-2)
      } else {
        Toast.fail(response.Message)
      }
    }
  }

  @action PageInitialization = async () => {
    Load.loading(1, '加载中')
    let response = await post(api.AREALIST)
    if (response.Success) {
      Load.loading(2, '加载完成')
      response.Value.map(item => {
        this.addressList.push(new AddressModel(item))
      })
    }
  }
}
